package com.bitantenna;

import java.util.HashMap;
import java.util.Map;

import utils.Utils;

import com.bitantenna.holepunch.HolePunchInterested;

public class SpotHolePunchTracker implements HolePunchInterested {
	private Spot spot;
	private Map<String,SpotInfo> partialSpots=new HashMap<String,SpotInfo>();
	public SpotHolePunchTracker(Spot s) {
		spot=s;
	}
	@Override
	public void onHolePunchInformation(Map<String,String> command,
			PortAddress sourcePrivatePortAddress,
			PortAddress sourcePublicPortAddress,
			PortAddress targetPrivatePortAddress,
			PortAddress targetPublicPortAddress) {
				
		String targetChannel=command.get("target_channel");

		//System.err.println("holepunch:"+targetChannel+" address:"+targetPublicPortAddress);

		SpotInfo node=partialSpots.get(command.get("target_id"));
		if (node==null) { // ya hay un nodo parcialmente registrado (le falta algun port)
			node=new SpotInfo(-1, new PortAddress(Utils.localIpAddress(),-1),new PortAddress(Utils.localIpAddress(),-1)); // TODO inicializamos parcialmente sin informacion coherente pensar mejor.			 
		}
		if ("producer".equals(targetChannel)) node.producerPortAddress(targetPublicPortAddress);
		if ("consumer".equals(targetChannel)) node.consumerPortAddress(targetPublicPortAddress);
		
		
		System.err.println("**CHECK_REGISTERS: consumers:"+spot.consumers().size());
		
		if (node.consumerPortAddress().port()!=-1 && node.producerPortAddress().port()!=-1) { //ya tenemos toda la info, registramos el nodo.			
			spot.registerConsumer(node);
			partialSpots.remove(command.get("target_id"));
			System.err.println("**CONFIRM_REGISTER: consumers:"+spot.consumers().size());			
		} else {
			partialSpots.put(command.get("target_id"), node);
			System.err.println("** PARTIAL_REGISTER:"+command.get("target_id")+" node:"+node);
		}
		

	}

}
